/**
 * 对话模型
 * 定义两个用户之间的对话
 */
const mongoose = require('mongoose');

const conversationSchema = new mongoose.Schema({
  participants: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  }],
  latestMessage: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Message'
  },
  unreadCount: {
    type: Number,
    default: 0
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
}, {
  timestamps: true
});

// 确保participants数组永远只有两个用户
conversationSchema.pre('save', function(next) {
  if (this.participants.length !== 2) {
    const error = new Error('对话必须有且仅有两个参与者');
    return next(error);
  }
  next();
});

// 创建复合索引，确保两个用户之间只有一个对话
conversationSchema.index({ participants: 1 }, { unique: true });

module.exports = mongoose.model('Conversation', conversationSchema); 